/**
 * usage node reg_cli.js server=192.168.102.136:8080 order=1
 */
var request = require('request');


var args = {};
process.argv.forEach(function(val, index, array) {
	// 0: node
	// 1 reg_cli.js
	// 2 server=192.168.102.136
	// 3 order=1
	// console.log('val=' + val);
	if (val.indexOf('=') >= 0) {
		var kv = val.split('=');
		args[kv[0]] = kv[1]
	}
});

console.log(args);
if (!args.server || !args.order) {
	console.log('usage : node reg_cli.js server=192.168.102.136:8080 order=1');
	return;
}

function __getIp() {
	var ifaces = require('os').networkInterfaces();
	var ips = {};
	for (var dev in ifaces) {
		ifaces[dev].forEach(function(details) {
			if (details.family === 'IPv4') {
				ips[dev] = details.address;
			}
		});
	}
	return ips.eth0 || ips.wlan0;
}
console.log('__getIp:', __getIp());

sendRequest();

// get param from console
function sendRequest() {
	var localIp = __getIp();
	console.log('localIp:', localIp);
	if (!localIp) {
		process.nextTick(function() {
			setTimeout(sendRequest.bind(this), 1000);
		});
		return;
	}
	var url = 'http://' + args.server + '?order=' + args.order + '&ip=' + localIp;
	console.log('sendRequest: ' + url);
	request(url, function(err, res, body) {
		handleReqResult(body);
	});
}

function handleReqResult(body) {
	console.log('handleReqResult: body=', body);
	var json = JSON.parse(body);
	if (json.ready) {
		allRegisterDone(json.info);
	} else {
		process.nextTick(function() {
			setTimeout(sendRequest.bind(this), 1000);
		});

	}
}

// start the .sh, config all(zookeeper)
function allRegisterDone(info) {
	config_zookeeper(args.order, info[1], info[2], info[3]);
	// var exec = require('child_process').exec;
	// // usage ./thisfile.sh order ip1 ip2 ip3
	// var cmd = '/tmp/all_conf.sh ' + args.order + ' ' + info[1] + ' ' + info[2] + ' ' + info[3];
	// console.log(cmd);
	// exec(cmd, function(error, stdout, stderr) {
	// 	console.log('register done');
	// 	// if exit, the container exits too, so we need do sth
	// 	config_zookeeper(args.order, info[0], info[1], info[2]);
	// });
}


function bg() {
	setTimeout(function() {
		console.log('node' + args.order + ' , ip=' + __getIp() + ' still alive');
		bg();
	}, 5000);
}

var fs = require('fs');

function config_zookeeper(order, h1, h2, h3, cb) {
	var __file1 = '/opt/zookeeper/conf/zoo.cfg';
	var __file2 = '/var/lib/zookeeper/myid';

	var zkCfg_pattern =
		"tickTime=2000\n" +
		"initLimit=10\n" +
		"syncLimit=5\n" +
		"dataDir=/var/lib/zookeeper\n" +
		"clientPort=2181\n" +
		"server.1=$h1:2888:3888\n" +
		"server.2=$h2:2888:3888\n" +
		"server.3=$h3:2888:3888";

	var cfg = zkCfg_pattern.replace('$h1', h1);
	cfg = cfg.replace('$h2', h2);
	cfg = cfg.replace('$h3', h3);

	fs.writeFile(__file1, cfg, function(err, res) {
		if (err) {
			console.log('error: config zookeeper fail, order =' + order);
			return;
		}
		fs.writeFile(__file2, '' + order, function(err2, res2) {
			if (err2) {
				console.log('error: config zookeeper myid, order =' + order);
				return;
			}
			console.log('zookeeper config done');
			config_kafka(order, h1, h2, h3);
		});
	});
}

function config_kafka(order, h1, h2, h3) {
	var __file1 = '/opt/kafka/config/server.properties';
	var kafkaCfg_pattern =
		"broker.id=$id\n" +
		"host.name=$myip\n" +
		"port=9092\n" +
		"num.network.threads=3\n" +
		"num.io.threads=8\n" +
		"socket.send.buffer.bytes=102400\n" +
		"socket.receive.buffer.bytes=102400\n" +
		"socket.request.max.bytes=104857600\n" +
		"log.dirs=/tmp/kafka-logs\n" +
		"num.partitions=1\n" +
		"num.recovery.threads.per.data.dir=1\n" +
		"log.retention.hours=168\n" +
		"log.segment.bytes=1073741824\n" +
		"log.retention.check.interval.ms=300000\n" +
		"log.cleaner.enable=false\n" +
		"zookeeper.connect=$h1:2181,$h2:2181,$h3:2181/kafka\n" +
		"zookeeper.connection.timeout.ms=6000";

	var cfg = kafkaCfg_pattern.replace('$id', order);
	cfg = cfg.replace('$myip', __getIp());
	cfg = cfg.replace('$h1', h1);
	cfg = cfg.replace('$h2', h2);
	cfg = cfg.replace('$h3', h3);

	fs.writeFile(__file1, cfg, function(err, res) {
		if (err) {
			console.log('error: config kafka fail, order =' + order);
			return;
		}

		console.log('kafka config done');
		config_storm(order, h1, h2, h3);
	});
}



function config_storm(order, h1, h2, h3) {
	var __file1 = '/opt/storm/conf/storm.yaml';
	var stormCfg_pattern =
		'storm.zookeeper.servers:\n' +
		'    - "$h1"\n' +
		'    - "$h2"\n' +
		'    - "$h3"\n' +
		'nimbus.host: "$h1"';

	var cfg = stormCfg_pattern.replace('$h1', h1);
	cfg = cfg.replace('$h1', h1);
	cfg = cfg.replace('$h2', h2);
	cfg = cfg.replace('$h3', h3);
	fs.writeFile(__file1, cfg, function(err, res) {
		if (err) {
			console.log('error: config storm fail, order =' + order);
			return;
		}

		console.log('storm config done');
	});
}